/*
 * FileHandler.java
 *
 * Created on April 10, 2007, 11:14 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.group1E.handlers;

import edu.byu.isys413.group1E.data.*;
import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import org.apache.commons.fileupload.FileItem;
/**
 * This class handles operations needed for saving 
 * and reading a File object to and from the BackupData table.
 * @author Travis Kulbeth
 */
public class FileHandler {
    
    private static FileHandler instance = null;
    
    /** Creates a new instance of FileHandler */
    public FileHandler() {
    }
    
    /**
     *gets you an instance of FileHandler
     *
     * @return instance of FileHandler
     */
    public static synchronized FileHandler getInstance() {
        if (instance == null) {
            instance = new FileHandler();
        }
        return instance;
    }
    
    /**
     * Saves a given file to the database.
     * @param memberID Contains the id of the member for which the file will be saved
     * @param status contains the status of the file to be saved ("permanent" for permanent backup storage,
     * "prints" for temporary storage until printed).
     * @param item contains the file to be saved
     * @return the guid for the file
     */
    public String saveFileToDB(FileItem item, String memberID, String status){
        String guid = null;
        try {
            BackupDataBO bkData = BackupDataDAO.getInstance().create();
            guid = bkData.getId();
            //get today's date for the begin date
            Calendar cal = Calendar.getInstance();
            Date today = cal.getTime();
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            String todayDate = fmt.format(today);
            
            //get the file's extension
            String filename = item.getName();
            String ext = filename.substring((filename.lastIndexOf('.')+1),filename.length());
            
            //build the object's metadata
            bkData.setDateUploaded(todayDate);
            bkData.setExt(ext);
            bkData.setFileName(filename);
            bkData.setFileSize(item.getSize());
            bkData.setFileType(item.getContentType());
        System.out.println(bkData.getFileType());
            bkData.setMembershipID(memberID);
            bkData.setStatus(status);
            
            //save the metaData to the dB
            Connection conn = ConnectionPool.getInstance().get();
            BackupDataDAO.getInstance().save(bkData, conn);
            
            //get the input stream of bytes from the file
            byte[] b = item.get();
            ByteArrayInputStream stream = new ByteArrayInputStream(b);
            
            //save the file to the new line in the database
            PreparedStatement pstmt = conn.prepareStatement("UPDATE BACKUPDATA SET fileObject = ? WHERE BackupID = ?");
            pstmt.setBinaryStream(1, (InputStream)stream, b.length);
            pstmt.setString(2, bkData.getId());
            pstmt.executeUpdate();
            
            ConnectionPool.getInstance().release(conn);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return guid;
    }
    
    /**
     * reads the actual file out of the database according to the guid provided.
     * @param id contains the id of the file record from which the file will be read
     * @return a ResultSet that contains the file and relevant information.
     */
    public ResultSet readFileByGUID(String id){
        ResultSet rs = null;
        try {
            Connection conn = ConnectionPool.getInstance().get();
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM BACKUPDATA WHERE BackupID = ?");
            pstmt.setString(1, id);
            rs = pstmt.executeQuery();
            
            ConnectionPool.getInstance().release(conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (ConnectionPoolException ex) {
            ex.printStackTrace();
        }
        return rs;
    }
}
